package com.firefighting.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.firefighting.entity.Enterprise;
import com.firefighting.entity.Role;
import com.firefighting.entity.User;
import com.firefighting.entity.UserBasicInfo;
import com.firefighting.service.EnterpriseService;
import com.firefighting.service.RoleService;
import com.firefighting.service.UserBasicInfoService;
import com.firefighting.service.UserService;
import com.firefighting.util.AutogenerationAccount;

@Controller
@RequestMapping("/Enterprise")
public class EnterpriseController
{
	@Autowired
	EnterpriseService enterpriseService;
	
	@Autowired
	RoleService roleService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	private UserBasicInfoService userbasic;
	@Autowired
	private UserService userSer;
	
	private String province = new String("");
	private String city = new String("");
	private String area = new String("");
	
	//zxt 点击左侧导航栏“管理企业基本信息”，跳转到该模块主界面
	@RequestMapping("index")
	public String index(HttpServletRequest request,Model model)
	{
		User user = (User) request.getSession().getAttribute("currentUser");
		String username = user.getUsername();
		int enterpriseId = userbasic.queryEnterpriseIdByUsername(username);
		String rolename = user.getRoleName();
		//System.out.println("rolename = " + rolename);
		Enterprise enterprise = enterpriseService.getEneterpriseById(enterpriseId);
		
		if(!enterprise.equals(null))
		{
			model.addAttribute("message", "true");
			model.addAttribute("content", enterprise);
		}
		else
		{
			model.addAttribute("message", "false");
		}
		
		if(rolename.equals("企业管理员"))
		{
			return "enterprise/editForEnterAdmin";
		}
		
		return "enterprise/enterprise";
	}
	
	
	/**
	 * @author zhyan
	 * @Date 2018.6.4 16:40
	 * @param id 企业id
	 * @return 企业信息
	 */
	@RequestMapping("getEnterpriseInfo")
	//public @ResponseBody() Map<String,Object> getEnterpriseInfo(@RequestParam("Id") int id)
	private String getEnterpriseInfo(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		Enterprise enterInfo = enterpriseService.getEneterpriseById(id);
		
		model.addAttribute("content", enterInfo);
		return "enterprise/viewEnterprise";
	}
	
	//张晗   添加企业
	@RequestMapping("/addEnterprise")
	public String addEnterprise(HttpServletRequest request, Model model)
	{
		//System.out.println("进入：");
		String name = request.getParameter("name");
		String identify = request.getParameter("identify");
		String provience = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String address = request.getParameter("address");
		String qualiffication = request.getParameter("qualification");
		String legalName = request.getParameter("legalName");
		String legalPhone = request.getParameter("legalPhone");
		String technicalDirector = request.getParameter("technicalDirector");
		String technicalPhone = request.getParameter("technicalPhone");
		String sevicePhone = request.getParameter("sevicePhone");
		
		String empNum = request.getParameter("employeNumber");
		int empNumber = Integer.parseInt(empNum);
		
		Enterprise e = new Enterprise();
		
		e.setAddress(address);
		e.setArea(area);
		e.setCity(city);
		e.setEmployeNumber(empNumber);
		e.setIdentify(identify);
		e.setName(name);
		e.setProvince(provience);
		e.setQualification(qualiffication);
		e.setLegalName(legalName);
		e.setLegalPhone(legalPhone);
		e.setTechnicalDirector(technicalDirector);
		e.setTechnicalPhone(technicalPhone);
		e.setServicePhone(sevicePhone);
		
		enterpriseService.addEnterprise(e);
		
		return "enterprise/enterprise";
	}
	
	//张晗  获取人员账号列表
	//韩佳迪 修改获取人员账号列表
	@RequestMapping("/getPersonList")
	public String getPersonList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
			
		List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
			
		//获取登陆用户
		User user =	(User)request.getSession().getAttribute("currentUser");
		//根据用户获取用户角色
		int roleId = user.getRoleid();
		//获取用户所属企业id
		System.out.println("user.getUsername()---"+user.getUsername());
		Integer enterId = userbasic.getEnterId(user.getUsername());
		String addJsp = null;
		switch(roleId){
			case 1://企业负责人
				result = userbasic.getPersonList(enterId);
				addJsp = "account/accountList";
				break;
			case 2://项目负责人
				result = userbasic.getPersonList(enterId);
				addJsp = "account/accountList";
				break;
			case 9://消防总队
				String enterPro = userbasic.getProvince(user.getUsername());
				System.out.println("enterPro---"+enterPro);
				result = userbasic.getProPersonList(enterPro);
				addJsp = "enterprise/EnterPerList";
				break;
			case 10://消防支队
				String enterCity = userbasic.getCity(user.getUsername());
				result = userbasic.getCityPersonList(enterCity);
				addJsp = "account/accountList";
				break;
			case 11://平台管理员
				result = userbasic.getAllPersonList();
				addJsp = "account/accountList";
				break;
		}
			
		System.out.println(result.toString());
		//System.out.println(result.toString());
		ObjectMapper objectMapper = new ObjectMapper();
		model.addAttribute("personList", objectMapper.writeValueAsString(result));
		
		return addJsp;
			
	}
	//韩佳迪 消防支队根据企业id获取人员账号列表
		@RequestMapping("/fireGetEnterPersonList")
		public String fireGetEnterPersonList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
					
			List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
							
					
			Integer enterId = Integer.valueOf(request.getParameter("id"));
			String addJsp = null;
			result = userbasic.getPersonList(enterId);
			addJsp = "enterprise/personListByEnter";
			System.out.println(result.toString());
			//System.out.println(result.toString());
			ObjectMapper objectMapper = new ObjectMapper();
			model.addAttribute("personList", objectMapper.writeValueAsString(result));
						
			return addJsp;
						
		}
	//修改维保企业状态	
	@RequestMapping("changeEnterStatus")
	@ResponseBody
	public String changeEnterStatus(HttpServletRequest request,Model model){
		HashMap<String,Object> map = new HashMap<String,Object>();
		String account = request.getParameter("account");
		String status = userbasic.getInfoByAccount(account).getStatus();
		int enterId = userbasic.queryEnterpriseIdByUsername(account);
		if (status.equals("停止")) {
			status = "开启";
		}else if (status.equals("开启")) {
			status = "停止";
		}
		userbasic.updateStatusByEnterId(enterId,status);
		map.put("flag", true);
		String json = JSONArray.toJSONString(map);
		return json;
	}
	//修改消防支队状态	
	@RequestMapping("changeFireStatus")
	@ResponseBody
	public String changeFireStatus(HttpServletRequest request,Model model){
		HashMap<String,Object> map = new HashMap<String,Object>();
		String account = request.getParameter("account");
		String status = userbasic.getInfoByAccount(account).getStatus();
		if (status.equals("停止")) {
			status = "开启";
		}else if (status.equals("开启")) {
			status = "停止";
		}
		userbasic.updateStatusById(account,status);
		map.put("flag", true);
		String json = JSONArray.toJSONString(map);
		return json;
	}
	//韩佳迪 消防总队获取该省的消防支队人员列表
	@RequestMapping("/getFirePersonList")
	public String getFirePersonList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
		
		List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		
		//获取登陆用户
		User user =	(User)request.getSession().getAttribute("currentUser");
		//根据用户获取用户角色
		@SuppressWarnings("unused")
		int roleId = user.getRoleid();
		//获取用户所属企业id
		//System.out.println("user.getUsername()---"+user.getUsername());
		@SuppressWarnings("unused")
		Integer enterId = userbasic.getEnterId(user.getUsername());
		String addJsp = null;
		String enterPro = userbasic.getProvince(user.getUsername());
		//System.out.println("enterPro---"+enterPro);
		result = userbasic.getFireProPersonList(enterPro);
		System.out.println("result "+result.toString());
		addJsp = "enterprise/FirePerList";
		//System.out.println(result.toString());
		//System.out.println(result.toString());
		ObjectMapper objectMapper = new ObjectMapper();
		model.addAttribute("personList", objectMapper.writeValueAsString(result));
		
		return addJsp;
		
	}
		//韩佳迪 消防总队获取该省的消防支队人员列表
		@RequestMapping("/getFirePersonInfoList")
		public String getFirePersonInfoList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
					
			List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
					
			//获取登陆用户
			User user =	(User)request.getSession().getAttribute("currentUser");
			//根据用户获取用户角色
			@SuppressWarnings("unused")
			int roleId = user.getRoleid();
			//获取用户所属企业id
			//System.out.println("user.getUsername()---"+user.getUsername());
			@SuppressWarnings("unused")
			Integer enterId = userbasic.getEnterId(user.getUsername());
			String addJsp = null;
			String enterPro = userbasic.getProvince(user.getUsername());
			//System.out.println("enterPro---"+enterPro);
			result = userbasic.getFireProPersonList(enterPro);
			System.out.println("result "+result.toString());
			addJsp = "fireTeam/fireTeam";
			//System.out.println(result.toString());
			//System.out.println(result.toString());
			ObjectMapper objectMapper = new ObjectMapper();
			model.addAttribute("personList", objectMapper.writeValueAsString(result));
					
			return addJsp;
					
		}
	
		//张晗   
		/**
		 * @author Liuxc
		 * 
		 * @function 根据用户所属企业返回
		 * 
		 * */
		@RequestMapping("/getEnterprise")
		public String getEnterprise(Model model,HttpServletRequest request){
			HttpSession session = request.getSession();
			User currentUser = (User) session.getAttribute("currentUser");
			if(currentUser.getRoleid()==1||currentUser.getRoleid()==2){
				int enterprise_id = userbasic.queryEnterpriseIdByUsername(currentUser.getUsername());
				List<Enterprise> enterList = new ArrayList<Enterprise>();
				enterList.add(enterpriseService.getEneterpriseById(enterprise_id));
			
				model.addAttribute("enterList", enterList);
			}
			else {
				//获取所有企业
				List<Enterprise> enterList = enterpriseService.getAllEnterprise();
				model.addAttribute("enterList", enterList);
			}
			
			//获取所有角色
			List<Role> roleList = roleService.getAllRole();
			model.addAttribute("roleList", roleList);
			return "account/addAccount";
			
		}
		@RequestMapping("/getFireEnterprise")
		public String getFireEnterprise(Model model,HttpServletRequest request){			
			return "account/addFire";
			
		}
	
		/**
		 * @author Liuxc
		 * @function 增加账号
		 * */
		@RequestMapping("/addEnterPerson")
		@ResponseBody
		public String addEnterPerson(HttpServletRequest request, Model model){
			HashMap<String,Object> map = new HashMap<String,Object>();
			User user = new User();
			UserBasicInfo uBasic = new UserBasicInfo();
	        //获取数据
			String name = request.getParameter("name");//名字
			String password  = "123456";//初始密码
			String roleId = request.getParameter("roleId");//角色id
			String roleShort = roleService.getShortByRoleId(Integer.parseInt(roleId));//角色缩写
			String province = request.getParameter("province")==null?"":request.getParameter("province");//省
			String city = request.getParameter("city")==null?"":request.getParameter("city");//市
			String area = request.getParameter("area")==null?"":request.getParameter("area");//区
			String status = request.getParameter("status")==null?"":request.getParameter("status");//状态
			String enterpriseName = request.getParameter("enterpriseName")==null?"":request.getParameter("enterpriseName");//状态
			
			
			String gender = request.getParameter("gender")==null?"":request.getParameter("gender");
			String age = request.getParameter("age")==null?"":request.getParameter("age");
			String phoneNum = request.getParameter("phone_number")==null?"":request.getParameter("phone_number");
			String identity  = "";
			String enterpriseId = request.getParameter("enterprise_id")==null?"":request.getParameter("enterprise_id");
			

			String identificationCard = request.getParameter("identification_card")==null?"":request.getParameter("identification_card");
			String technicalLevel = request.getParameter("technical_level")==null?"":request.getParameter("technical_level");
			String position = request.getParameter("position")==null?"":request.getParameter("position");
			
			
			//生成账号
			int userId = userService.getMaxId()+1;
			String userName  = null;
			System.out.println("roleid----"+roleId);
			userName = AutogenerationAccount.firefightingAccountFormat(roleShort, userId);
			
			
			//添加user用户信息
			user.setPassword(password);
			user.setUsername(userName);
			user.setRoleid(Integer.parseInt(roleId));
			//用户通用基本信息
			
			uBasic.setRoleId(Integer.parseInt(roleId));
			uBasic.setLoginId(userName);
			uBasic.setPhoneNumber(phoneNum);
			uBasic.setName(name);		
			Date date = new Date();
			uBasic.setCreationTime(date);
            uBasic.setStatus(status);
            
            
			if(Integer.parseInt(roleId) == 9){//若为消防总队
				if(userbasic.getInfoByRoleAndProvence(roleId,province).size()!=0){//若该省消防总队已存在账号
					
					map.put("error", "该省消防总队已存在账号");
					return JSONArray.toJSONString(map);
					
					}else{
						identity = "消防总队";
						uBasic.setProvince(province);
						uBasic.setCity(city);
						uBasic.setArea(area);
						uBasic.setPersonIdentity(identity);
						userSer.insertUserAndInfo(user,uBasic);//插入用户以及用户角色
				}
				
			}else if(Integer.parseInt(roleId) == 10){//若为消防支队
				System.out.println("若为消防支队roleid----"+roleId);
	            if(userbasic.getInfoByRoleAndCity(roleId,city).size()!=0){//若该省消防支队已存在账号
	            	System.out.println("若为消防支队已存在账号----"+roleId);
	            	map.put("error",1);
					return JSONArray.toJSONString(map);
				}else{
				    identity = "消防支队";
					uBasic.setProvince(province);
					uBasic.setCity(city);
					uBasic.setArea(area);
					uBasic.setPersonIdentity(identity);		
					userSer.insertUserAndInfo(user,uBasic);//插入用户以及用户角色
				}
			}else if(Integer.parseInt(roleId) == 1){//若为企业管理员
				Enterprise enterprise = new Enterprise();
				enterprise.setName(enterpriseName);
				enterprise.setProvince(province);
				enterprise.setCity(city);
				enterprise.setArea(area);
				
				identity = "维保企业";
				uBasic.setProvince(province);
				uBasic.setCity(city);
				uBasic.setArea(area);
				uBasic.setPersonIdentity(identity);
				userSer.insertEnterpriseAndUserinfo(user,uBasic,enterprise);//插入用户以及用户角色
				
			}else{//若为其他角色
				identity = "维保企业";
				uBasic.setPersonIdentity(identity);
				uBasic.setAge(Integer.parseInt(age));
				uBasic.setEnterpriseId(Integer.parseInt(enterpriseId));
				uBasic.setGender(gender);
				uBasic.setIdentificationCard(identificationCard);
				uBasic.setTechnicalLevel(technicalLevel);
				uBasic.setPosition(position);
				userSer.insertUserAndInfo(user,uBasic);//插入用户以及用户角色
			}




			map.put("userName", userName);
			String json = JSONArray.toJSONString(map);
			//System.out.println(json);
			return json;
			
		}
	/**
	 * @author Liuxc
	 * 更改密码
	 * */
		@RequestMapping("changePassword")
		@ResponseBody
		public String changePassword(HttpServletRequest request,Model model){
			HashMap<String,Object> map = new HashMap<String,Object>();
			String userName = request.getParameter("userName");
			String password = request.getParameter("password");
			userSer.updatePasswordById(userName, password);
			map.put("flag", true);
			String json = JSONArray.toJSONString(map);
			return json;
		}
		
	
	//张彦 修改编辑功能，增加消防部门的对企业管理员的编辑
		//liuxc 增加更改密码。
		@RequestMapping("editEmployee")
		@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
		private String editEmployee(HttpServletRequest request, Model model)
		{	
			String name = request.getParameter("name");
			//System.out.println("editPerson-----"+name);
			String gender = request.getParameter("gender");
			String age = request.getParameter("age");
			String phoneNum = request.getParameter("phone_number");
			@SuppressWarnings("unused")
			String password  = request.getParameter("password");
			String identity  = request.getParameter("personIdentity");
			String enterpriseId = request.getParameter("enterprise_id");
			System.out.println("enterpriseId "+enterpriseId);
			String roleId = request.getParameter("roleId");
			System.out.println("roleid "+roleId);
			String identificationCard = request.getParameter("identification_card");
			String position = request.getParameter("position");
			String technicalLevel = request.getParameter("technical_level");
			String status = request.getParameter("status");
			String type = request.getParameter("type");
			//System.out.println("type "+type);
			String province = request.getParameter("province");
			String city = request.getParameter("city");
			String area = request.getParameter("area");
			String id = request.getParameter("id");
			UserBasicInfo u = userbasic.getInfoById(Integer.parseInt(id));
			if(password!=null){
				userService.updatePasswordById(u.getLoginId() , password);//更新账号密码
			}
			
			Date date = new Date();
			u.setLastChangeTime(date);
			if (type.equals("1")) {
				System.out.println("type1-----"+type);
				//消防部门添加
				u.setName(name);
				u.setPhoneNumber(phoneNum);
				u.setPersonIdentity(identity);
				u.setRoleId(Integer.parseInt(roleId));
				u.setProvince(province);
				u.setCity(city);
				u.setArea(area);
				u.setStatus(status);
				//添加企业用户信息
				userbasic.fireEditUserbasic(u);
				User user =	(User)request.getSession().getAttribute("currentUser");
				System.out.println("user.getUsername()---"+user.getUsername());
				@SuppressWarnings("unused")
				Integer enterId = userbasic.getEnterId(user.getUsername());
				String addJsp = null;
				String enterPro = userbasic.getProvince(user.getUsername());
				System.out.println("enterPro---"+enterPro);
				List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
				result = userbasic.getFireProPersonList(enterPro);
				addJsp = "account/fireAccount";
				System.out.println(result.toString());
				//System.out.println(result.toString());
				ObjectMapper objectMapper = new ObjectMapper();
				try {
					model.addAttribute("personList", objectMapper.writeValueAsString(result));
				} catch (org.codehaus.jackson.JsonGenerationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (org.codehaus.jackson.map.JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return addJsp;
			}
			else if (type.equals("2")) {
				System.out.println("type2-----"+type);
				//企业添加
				//u.setIdentity(identity);
				u.setName(name);
				u.setGender(gender);
				u.setAge(Integer.parseInt(age));
				u.setPhoneNumber(phoneNum);
				u.setPersonIdentity(identity);
				u.setEnterpriseId(Integer.parseInt(enterpriseId));
				u.setRoleId(Integer.parseInt(roleId));
				u.setIdentificationCard(identificationCard);
				u.setPosition(position);
				u.setTechnicalLevel(technicalLevel);
				u.setStatus(status);
				//添加企业用户信息
				userbasic.EnterEditUserbasic(u);userbasic.fireEditUserbasic(u);
				User user =	(User)request.getSession().getAttribute("currentUser");
				System.out.println("user.getUsername()---"+user.getUsername());
				Integer enterId = userbasic.getEnterId(user.getUsername());
				String addJsp = null;
				List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
				result = userbasic.getPersonList(enterId);
				addJsp = "account/accountList";
				System.out.println(result.toString());
				//System.out.println(result.toString());
				ObjectMapper objectMapper = new ObjectMapper();
				try {
					model.addAttribute("personList", objectMapper.writeValueAsString(result));
				} catch (org.codehaus.jackson.JsonGenerationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (org.codehaus.jackson.map.JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return addJsp;
			}
			
			
			return "account/accountList";
		}
	
	
	
	/**
	 * @author zhyan
	 * @Date 2018.6.4 17:26
	 * @function 更新企业信息
	 * 
	 * @param id 企业id
	 * @param Name 企业名称
	 * @Param Identify 企业身份
	 * @Param Province 省
	 * @Param City 市
	 * @Param Area 区/县
	 * @Param Address 详细地址
	 * @Param Qualification 企业资质
	 * @Param Employe_number 从业人数
	 * @return 修改是否成功
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("updateEnterpriseInfo")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	private String updateEnterprise(MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String identify = request.getParameter("identify");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String address = request.getParameter("address");
		String qualification = request.getParameter("qualification");
		String legalName = request.getParameter("legalName");
		String legalPhone = request.getParameter("legalPhone");
		String technicalDirector = request.getParameter("technicalDirector");
		String technicalPhone = request.getParameter("technicalPhone");
		String sevicePhone = request.getParameter("sevicePhone");
		int employeNumber = Integer.parseInt(request.getParameter("employeNumber"));
		String accessory = null;
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		
		if(!fileName.equals(null) && !fileName.equals(""))
		{
			File dir = new File(path, fileName);
			
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			// MultipartFile自带的解析方法
			file.transferTo(dir);
			accessory = dir.toString();
		}
		
		Enterprise enterprise = new Enterprise();
		enterprise.setId(id);
		enterprise.setName(name);
		enterprise.setIdentify(identify);
		enterprise.setProvince(province);
		enterprise.setCity(city);
		enterprise.setArea(area);
		enterprise.setAddress(address);
		enterprise.setQualification(qualification);
		enterprise.setLegalName(legalName);
		enterprise.setLegalPhone(legalPhone);
		enterprise.setTechnicalDirector(technicalDirector);
		enterprise.setTechnicalPhone(technicalPhone);
		enterprise.setServicePhone(sevicePhone);
		enterprise.setEmployeNumber(employeNumber);
		enterprise.setCertificatePicture(accessory);
		
		enterpriseService.updateEnterpriseInfo(id, enterprise);//更新企业信息
		
		return "enterprise/enterprise";
	}
	
	/**
	 * @author zhyan
	 * @function 根据企业id查询企业信息
	 * @param id 企业id
	 * @return
	 */
	@RequestMapping("getSingleEnterprise")
	private String getEmployee(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		Enterprise content = enterpriseService.getEneterpriseById(id);
		model.addAttribute("content", content);
		
		return "enterprise/editEnterprise";
	}
	
	
	
	/**
	 * @function 根据省市县等位置内容查询企业信息
	 * @author zhyan
	 * @date 2018.6.5 15:09
	 * @param province 省
	 * @param city 市
	 * @param area 县
	 * @return
	 * @throws IOException 
	 * @throws org.codehaus.jackson.map.JsonMappingException 
	 * @throws org.codehaus.jackson.JsonGenerationException 
	 */
	@RequestMapping("queryEnterpriseList")
	private String queryEnterpriseList(HttpServletRequest request, Model model) throws org.codehaus.jackson.JsonGenerationException, org.codehaus.jackson.map.JsonMappingException, IOException
	{
		this.province = request.getParameter("province");
		this.city = request.getParameter("city");
		this.area = request.getParameter("area");
		
		if(this.city.equals("选择市"))
			this.city = "";
		if(this.area.equals("选择县/区"))
			this.area = "";
		
		@SuppressWarnings("rawtypes")
		List<HashMap> content = enterpriseService.queryEnterpriseByLocation(province, city, area);
		if(content.size() > 0)
		{
			model.addAttribute("message", "true");//有查询结果，将结果放在content中返回传输到前端
			ObjectMapper objectMapper = new ObjectMapper();
			model.addAttribute("content", objectMapper.writeValueAsString(content));
		}
		else
		{
			model.addAttribute("message", "false");//无查询结果
		}
		
		this.province = new String("");
		this.city = new String("");
		this.area = new String("");
		
		return "enterprise/enterprise";
	}
	
	/**
	 * @author Liuxc
	 * @function 根据用户id查询用户信息
	 * 

	 * 
	 */
	@RequestMapping("accountEdit")
	private String getUserById(HttpServletRequest request, Model model){
		String userName = request.getParameter("userName");
		//System.out.println(userName);
		User user = userService.getUserIdByLoginId(userName);
		UserBasicInfo userBasicInfo = userbasic.getInfoByAccount(userName);
		List<Enterprise> enterList = new ArrayList<Enterprise>();
		enterList.add(enterpriseService.getEneterpriseById(userBasicInfo.getEnterpriseId()));
		model.addAttribute("user",user );
		model.addAttribute("userBasicInfo",userBasicInfo );
		model.addAttribute("enterList",enterList );
		return "account/editAccount";
	}
	@RequestMapping("accountFireEdit")
	private String accountFireEdit(HttpServletRequest request, Model model){
		String name = request.getParameter("login_id");
		//System.out.println(userName);
		User user = userService.getUserIdByLoginId(name);
		UserBasicInfo userBasicInfo = userbasic.getInfoByAccount(name);
		model.addAttribute("user",user );
		model.addAttribute("userBasicInfo",userBasicInfo );
		/*System.out.println(userBasicInfo.getIdentificationCard());
		System.out.println(userBasicInfo.getPhoneNumber());*/
		//System.out.println(userName);
		return "account/editFire";
	}
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @function admin权限
	 * @date 2018.6.7?
	 */
	@RequestMapping("updateEnterpriseForEnterAdmin")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	private String updateEnterpriseForEnterAdmin(MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException
	{
		User user = (User) request.getSession().getAttribute("currentUser");
		int id = user.getUserid();
		int enterpriseId = userbasic.getInfoByAccount(user.getUsername()).getEnterpriseId();
		String name = request.getParameter("name");
		String identify = request.getParameter("identify");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String address = request.getParameter("address");
		String qualification = request.getParameter("qualification");
		String legalName = request.getParameter("legalName");
		String legalPhone = request.getParameter("legalPhone");
		String technicalDirector = request.getParameter("technicalDirector");
		String technicalPhone = request.getParameter("technicalPhone");
		String sevicePhone = request.getParameter("sevicePhone");
		int employeNumber = Integer.parseInt(request.getParameter("employeNumber"));
		String accessory = null;
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		
		if(!fileName.equals(null) && !fileName.equals(""))
		{
			File dir = new File(path, fileName);
			
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			// MultipartFile自带的解析方法
			file.transferTo(dir);
			accessory = dir.toString();
		}
		
		Enterprise enterprise = new Enterprise();
		enterprise.setId(enterpriseId);
		enterprise.setName(name);
		enterprise.setIdentify(identify);
		enterprise.setProvince(province);
		enterprise.setCity(city);
		enterprise.setArea(area);
		enterprise.setAddress(address);
		enterprise.setQualification(qualification);
		enterprise.setLegalName(legalName);
		enterprise.setLegalPhone(legalPhone);
		enterprise.setTechnicalDirector(technicalDirector);
		enterprise.setTechnicalPhone(technicalPhone); 
		enterprise.setServicePhone(sevicePhone);
		enterprise.setEmployeNumber(employeNumber);
		enterprise.setCertificatePicture(accessory);
		
		enterpriseService.updateEnterpriseInfo(id, enterprise);//更新企业信息
		model.addAttribute("message", "true");//修改成功
		model.addAttribute("content", enterprise);
		
		return "enterprise/editForEnterAdmin";
	}
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws org.codehaus.jackson.map.JsonMappingException 
	 * @throws org.codehaus.jackson.JsonGenerationException 
	 * @function 根据用户角色展示企业信息列表
	 * @date 2018.6.10
	 */
	@RequestMapping("queryByRole")
	public String queryByRole(HttpServletRequest request, Model model) throws org.codehaus.jackson.JsonGenerationException, org.codehaus.jackson.map.JsonMappingException, IOException
	{
		ObjectMapper objectMapper = new ObjectMapper();
		//获取登陆用户
		User user =	(User)request.getSession().getAttribute("currentUser");
		//根据用户获取用户角色
		int roleId = user.getRoleid();
		switch(roleId)
		{
		case 11:
		case 9://消防总队
			String province = userbasic.getProvince(user.getUsername());
			@SuppressWarnings("rawtypes") List<HashMap> content = enterpriseService.queryByProvince(province);
			model.addAttribute("content", objectMapper.writeValueAsString(content));
			//return "fireTeam/fireTeam";
		    break;
			
		case 10://消防支队                                
			UserBasicInfo info = userbasic.getInfoByAccount(user.getUsername());
			String province1 = info.getProvince();
			String city = info.getCity();
			@SuppressWarnings("rawtypes") List<HashMap> content1 = enterpriseService.queryByProvinceAndCity(province1, city);
			model.addAttribute("content", objectMapper.writeValueAsString(content1));
			//return "fireTeam/fireTeam";
		}
		
		return "enterprise/enterprise";
	}
	
	/**
	 * @author zhyan
	 * @function 图片上传功能
	 * @date 2018.6.8
	 * @TIPS 仿网格化代码完成
	 */
	/*@RequestMapping("uploadPicture")
	private String uploadPicture(MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		File dir = new File(path, fileName);
		
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		
		String accessory = dir.toString();
		Enterprise record = enterpriseService.getEneterpriseById(id);
		record.setCertificatePicture(accessory);
		int number = enterpriseService.updateEnterpriseInfo(id, record);
		
		if(number > 0)
		{
			model.addAttribute("message", "true");//上传成功，将路径写入数据库
		}
		else
		{
			model.addAttribute("message", "false");//上传失败
		}
		
		return "";
	}*/
	
	/**
	 * @author zhyan
	 * @function 下载图片
	 * @date 2018.6.8
	 * @TIPS：仿网格化项目代码完成
	 */
	@RequestMapping("/down")
	public void down(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("id"));
		Enterprise record = enterpriseService.getEneterpriseById(id);
		String filePath = null;
		try
		{
			// 从数据库中获取凭证的完整文件路径
			filePath = record.getCertificatePicture();
			
			// 获取输入流
			InputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			// 获取文件名称
			String temp[] = filePath.replaceAll("\\\\", "/").split("/");
			String fileName = "";
			
			if (temp.length > 1)
			{
				fileName = temp[temp.length - 1];
			}
			
			// 设置文件下载头
			response.addHeader("Content-Disposition","attachment;filename=" + fileName);
			// 设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			int len = 0;
			
			while((len = bis.read()) != -1)
			{
				out.write(len);
				out.flush();
			}
			bis.close();
			out.close();
		}
		catch (Exception e)
		{
			response.sendRedirect(request.getContextPath() + "/Enterprise/downLoad.htm");//原因：使用的框架要求在跳转到控制器时，必须要在控制器的名字后面加.htm后缀
		}
	}
	
	/**
	 * @author zhyan
	 * @function 查询企业图片
	 * @date 2018.6.30
	 * @return
	 */
	@RequestMapping("certificatePicture")
	private String getCertificatePrcture(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		Enterprise enterprise = enterpriseService.getEneterpriseById(id);
		model.addAttribute("content", enterprise);
		
		return "enterprise/viewCerPic";
	}
	
	/**
	 * @author zhyan
	 * @function 图片下载错误处理方法
	 * @date 2018.6.30
	 */
	@RequestMapping("/downLoad")
	public String errorProcess()
	{
		//图片下载错误处理方法
		return "enterprise/error";
	}
}